/**
 * Created by Administrator on 2017/8/24.
 */

var map;
var busutil;
var htmlTable;

var hasBusNo = false;
var curItemNo = window.localStorage.getItem("curItemNo");
if (curItemNo == null) {
    //busStationMap没有传
    curItemNo = 0;
    window.localStorage.setItem("curItemNo", curItemNo);
}
var busNo = window.localStorage.getItem("busNo");
//busNo传了
if (busNo != null) {
    hasBusNo = true;
}
var hasStationName = false;
var stationName = window.localStorage.getItem("stationName");
if (stationName != null) {
    hasStationName = true;
}

var mySwiper;
var stationArr = [];
var stopCount;

//反向功能的curItemNo
var reverseItemNo;

$(document).ready(function () {
    initMap();
    initControl();

    //对面板进行声明
    $("#searchpanel").trigger("updatelayout");
    $("#resultpanel").trigger("updatelayout");

    busutil = new BMap.BusLineSearch("杭州", {
        renderOptions: {panel: "itemResult"},
        onGetBusListComplete: function (buslist) {
            //为反向功能存储值
            var busNoName = buslist.getBusListItem(curItemNo).name;
            var index01 = busNoName.indexOf('(');
            var index02 = busNoName.indexOf('-');
            var curName = busNoName.substring(0,index01);
            var name01 = busNoName.substring(index01+1, index02);
            var name02 = busNoName.substring(index02+1,busNoName.length-1);
            if(name01==name02){
                reverseItemNo = curItemNo;
            }else{
                if(curItemNo>0){
                    var prev = buslist.getBusListItem(curItemNo-1).name;
                    var prevIndex = prev.indexOf('(');
                    var prevName = prev.substring(0,prevIndex);
                    if(prevName == curName){
                        reverseItemNo = curItemNo-1;
                    }else{
                        if(buslist.getBusListItem(curItemNo+1)!=undefined){
                            var next = buslist.getBusListItem(curItemNo+1).name;
                            var nextIndex = next.indexOf('(');
                            var nextName = next.substring(0,nextIndex);
                            if(nextName == curName){
                                reverseItemNo = parseInt(curItemNo) + 1;
                            }
                        }else{
                            //应该不可能发生
                        }
                    }
                }else{
                    reverseItemNo = parseInt(curItemNo) + 1;
                }
            }
            var lineNameList = buslist.KA;
            var html = [];
            for (var i in lineNameList) {
                html.push('<li><a href="javascript:void(0)" onclick="subgo(' + i + ' )">' + lineNameList[i].name +
                    '</a></li>');
            }
            var l_result = document.getElementById("l-result");
            l_result.innerHTML = '<ul>' + html.join('') + '</ul>';

            busutil.getBusLine(buslist.getBusListItem(curItemNo));
        },
        onGetBusLineComplete: function (busline) {
            //写线路的基本信息
            var index = busline.name.indexOf('(');
            var htmlTitle = busline.name.substring(0, index);

            $("#title").html(htmlTitle);

            var htmlPoints =
                '<div style="height: 40px;font-size:14px;"><img src="img/icons-road.png"style="width:22px;height:22px;vertical-align: middle;margin-right: 6px;">' + busline.name.substring(index + 1, busline.name.length - 1) + '</div>';

            var htmlTimes =
                '<div style="font-size: 12px;"><span style="color: #169bdb;">●</span><span>首班：' + busline.startTime
                + '</span><span style="color: #f77446;margin-left: 6px;">●</span><span>末班：' + busline.endTime +
                '</span><span style="margin-left: 6px;">票价：2元</span></div>';

            $.ajax({
                url: 'http://127.0.0.1:8083/app-server/busStationInfo',
                data: {"SL_id":1},
                type: 'get',
                datatype: 'json',
                async: 'false',
                success: function (json) {					
                    var busInfoList = json.station;
                    var nextStopArr = [];
                    var stopCountArr = [];
                    var stopTimeArr = [];
                    var stopDistanceArr = [];
                    for (var i in busInfoList) {
                        nextStopArr[i] = busInfoList[i].nextstop;
                        stopCountArr[i] = busInfoList[i].stopcount;
                        stopTimeArr[i] = busInfoList[i].distance;
                        stopDistanceArr[i] = busInfoList[i].time;
                    }
                    htmlTable =
                        '<div><table><tr><td align="center">最近的第1辆公交</td><td align="center">最近的第2辆公交</td></tr><tr><th colspan="2" style="border-bottom: 1px #2c2c2c solid"></th></tr><tr><td align="center">' + stopCountArr[0] + '站</td><td align="center">' + stopCountArr[1] + '站</td></tr><tr><td align="center">开往 ' + nextStopArr[0] + '</td><td align="center">到达 ' + nextStopArr[1] + '</td></tr><tr><td align="center">' + stopTimeArr[0] + '/' + stopDistanceArr[0] + '</td><td align="center">' + stopTimeArr[1] + '/' + stopDistanceArr[1] + '</td></tr><tr><th colspan="2" style="border-bottom: 1px #2c2c2c solid"></th></tr></table></div>';
                    $('.thumbs-title').html(htmlPoints + htmlTimes + htmlTable);
                }
            });


            //需要来画地图列表了
            var stations = busline.RB;
            var html = [];
            for (var i in stations) {
                stationArr[i] = stations[i].name;
                if (stationName==null) {
                    if (i == 0) {
                        html.push('<div class="swiper-slide"><img src="img/icons-pic-select.png"' +
                            ' onclick="divClick(this)" alt=""><div class="app-title" style="color:#ff8d30">' +
                            stations[i].name + '</div></div>');
                    } else {
                        html.push('<div class="swiper-slide"><img src="img/icons-pic.png"  onclick="divClick(this)" alt=""><div class="app-title">' +
                            stations[i].name + '</div></div>');
                    }
                } else {
                    if (stations[i].name == stationName) {
                        html.push('<div class="swiper-slide"><img src="img/icons-pic-select.png"' +
                            ' onclick="divClick(this)" alt=""><div class="app-title" style="color:#ff8d30">' +
                            stations[i].name + '</div></div>');
                    } else {
                        html.push('<div class="swiper-slide"><img src="img/icons-pic.png"  onclick="divClick(this)" alt=""><div class="app-title">' +
                            stations[i].name + '</div></div>');
                    }
                }
            }

            /*            $('.swiper-container').css("height", '400px');
             $('.swiper-container').css("width", '2000px');
             $('.swiper-wrapper').css("height", '100px');
             $('.swiper-wrapper').css("width", '2000px');*/
            $('.swiper-wrapper').html(html);

            $('.thumbs-cotnainer').each(function () {
                mySwiper = $(this).swiper({
                    slidesPerView: 'auto',
                    offsetPxBefore: 25,
                    offsetPxAfter: 10,
                    calculateHeight: true,
                    setWrapperSize: true,
                    freeMode: true
                })
            });
            getStopCount();
            mySwiper.swipeTo(stopCount, 500, false);
        },
        onBusLineHtmlSet: function () {
            $("#l-result ul li a").each(function (index, element) {
                if (index != curItemNo) {
                    $(element).css("color", "green");
                } else {
                    $(element).css("color", "blue");
                }
            });
        }
    });

    var img = document.createElement("img");
    img.style.cursor = 'pointer';
    img.setAttribute('src', 'img/reversebutton.png');
    img.setAttribute('width', '40px');
    img.setAttribute('height', '40px');
    /*    img.setAttribute('right', '0px');
     img.setAttribute('bottom', '80px');
     img.setAttribute('position', 'fixed');*/
    img.setAttribute('class', 'float');

    img.onclick = function (e) {
        curItemNo = reverseItemNo;
        window.localStorage.setItem('curItemNo', curItemNo);
        busutil.getBusList(busNo);
    };

    //直接再切换回busStationMap
    if (hasBusNo&&hasStationName) {
        $("#map").css("display", "none");
        /*window.localStorage.setItem("curItemNo", curItemNo);
         window.localStorage.setItem("busNo", busNo);*/
        busutil.getBusList(busNo);
        hasBusNo = false;
        hasStationName = false;
    }

    //进行搜索之后再切换回busStationMap
    $('#query').click(function () {
        $("#map").css("display", "none");
        busNo = $("#keyword").val();
        busutil.getBusList(busNo);
        window.localStorage.setItem("busNo", busNo);
        curItemNo = 0;
        $("#keyword").val("");
        $("#searchpanel").panel("close");
        $("#resultpanel").panel("open");
    });
});

function getStopCount() {
    if (stationName==null) {
        stopCount == 0;
        return false;
    } else {
        for (var i in stationArr) {
            if (stationArr[i] == stationName) {
                stopCount = i;
                return false;
            }
        }
    }
}

//初始化地图
initMap = function () {
    var mapOpts = {minZoom: 11, maxZoom: 17, enableHighResolution: true};
    map = new BMap.Map('map', mapOpts);
    map.centerAndZoom("杭州");
};

//初始化地图控件
initControl = function () {
    var navOpts = {anchor: BMAP_ANCHOR_BOTTOM_RIGHT, offset: new BMap.Size(50, 40), type: BMAP_NAVIGATION_CONTROL_ZOOM};
    var nav = new BMap.NavigationControl(navOpts);
    map.addControl(nav);

    /*    var scale = new BMap.ScaleControl();
     map.addControl(scale);*/

    var overOpts = {
        anchor: BMAP_ANCHOR_TOP_LEFT,
        offset: new BMap.Size(10, 10),
        size: new BMap.Size(100, 100),
        isOpen: false
    };
    var over = new BMap.OverviewMapControl(overOpts);
    map.addControl(over);

    /*    var mapTypeC = new BMap.MapTypeControl();
     map.addControl(mapTypeC);*/
};

function divClick(item) {
    //首先判断是否有使用select icon的img 将其还原  遍历
    $('.swiper-wrapper img').each(function (index, val) {
        if ($(val).attr('src') == 'img/icons-pic-select.png') {
            $(val).attr('src', 'img/icons-pic.png');
            $(val).next().css('color', 'black');
            return false;
        }
    });

    //设置此img
    $(item).attr('src', "img/icons-pic-select.png");
    $(item).next().css('color', '#ff8d30');
    stationName = $(item).next().html();
    window.localStorage.setItem('stationName', stationName);

    //ajax更改实时信息
    $.ajax({
        url: 'http://10.100.122.132/busStationInfo',
//                data: {"SL_id":sl_id},
        type: 'get',
        datatype: 'json',
        async: 'false',
        success: function (json) {
            var busInfoList = json.station;
            var nextStopArr = [];
            var stopCountArr = [];
            var stopTimeArr = [];
            var stopDistanceArr = [];
            for (var i in busInfoList) {
                nextStopArr[i] = busInfoList[i].nextstop;
                stopCountArr[i] = busInfoList[i].stopcount;
                stopTimeArr[i] = busInfoList[i].distance;
                stopDistanceArr[i] = busInfoList[i].time;
            }
            htmlTable =
                '<div><table><tr><td align="center">最近的第1辆公交</td><td align="center">最近的第2辆公交</td></tr><tr><th colspan="2" style="border-bottom: 1px #2c2c2c solid"></th></tr><tr><td align="center">' + stopCountArr[0] + '站</td><td align="center">' + stopCountArr[1] + '站</td></tr><tr><td align="center">开往 ' + nextStopArr[0] + '</td><td align="center">到达 ' + nextStopArr[1] + '</td></tr><tr><td align="center">' + stopTimeArr[0] + '/' + stopDistanceArr[0] + '</td><td align="center">' + stopTimeArr[1] + '/' + stopDistanceArr[1] + '</td></tr><tr><th colspan="2" style="border-bottom: 1px #2c2c2c solid"></th></tr></table></div>';
            $('.thumbs-title div:last').remove();
            $('.thumbs-title').append($(htmlTable));
        }
    });
}

function subgo(itemNo) {
    curItemNo = itemNo;
    window.localStorage.setItem("curItemNo", curItemNo);
    busutil.getBusList(busNo);
}